﻿using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Windows;
using System.Windows.Input;

namespace Auktionshuset
{
    public partial class LoginWindow
    {
        private string _error;
        private Connection _conn;

        public LoginWindow()
        {
            InitializeComponent();
        }

        private void Register_Click(object sender, RoutedEventArgs e)
        {
            RegisterWindow rw = new RegisterWindow(UsernameTextBox.Text, PasswordTextBox.Password) { Owner = this };
            bool? result = rw.ShowDialog();

            if (result != true) return;

            UsernameTextBox.Text = rw.UsernameTextBox.Text;
            PasswordTextBox.Password = rw.PasswordTextBox.Password;
        }

        private void Login_Click(object sender, RoutedEventArgs e)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;

            LoaderGrid.Visibility = Visibility.Visible;
            worker.RunWorkerAsync(new string[] {UsernameTextBox.Text, PasswordTextBox.Password});
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] arguments = (string[])e.Argument;

            string username = arguments[0];
            string password = arguments[1];

            _error = null;

            EndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 40404);
            try
            {
                Socket socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(ep);

                Connection conn = new Connection(socket);

                Response resp = conn.AttemptLogin(username, password);
                if (resp.Success)
                {
                    _conn = conn;
                }
                else
                {
                    _error = resp.Error;
                }
            }
            catch (SocketException exception)
            {
                _error = exception.Message;
            }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            LoaderGrid.Visibility = Visibility.Hidden;
            if (_error == null)
            {
                new MainWindow(_conn).Show();
                Close();
            }
            else
            {
                StatusTextBlock.Text = _error;
            }
        }

        private void Form_OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Login_Click(sender, e);
            }
        }
    }
}
